package com.allen.controller;

import com.allen.bean.User;
import com.allen.common.R;
import com.allen.service.UserService;
import com.allen.utils.SMSUtils;
import com.allen.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author dragon1006xu@gmail.com
 * @create 2022/2/19 16:18
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //1.获取手机号
        String phone = user.getPhone();
        //2.使用工具类生成验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        //3.使用短信发送工具类 发送验证码给用户
        //SMSUtils.sendMessage("瑞吉外卖","瑞吉",phone,validateCode.toString());
        log.info("【瑞吉外卖App】"+phone+"=>验证码：{}", validateCode);
        //4.为了方便和前台用户输入的验证码进行比对 所以要将生成的验证码存在session中
        //使用手机号作为session的key值
        session.setAttribute(phone, validateCode);
        //5.响应 发送验证码到前台
        return R.success(validateCode.toString());
    }

    @PostMapping("/login")
    //使用Map集合接收json格式参数
    public R login(@RequestBody Map map, HttpSession session) {
        log.info("map:{}", map);
        //1.获取用户输入的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //2.获取session中储存的验证码
        String validateCode = session.getAttribute(phone).toString();
        //3.比对用户输入的验证码和session中储存的验证码是否一致 一致登入成功
        if (validateCode != null && validateCode.equals(code)) {
            //如果比对成功，说明登录成功
            //4.登入成功后 4.1:根据手机号去user表中查询是否存在用户user 4.2:如果不存在，则添加到user表中
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            if (user == null) {
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            return R.success(user);
        }

        //5.不一致，登入失败
        return R.success("登入失败");
    }

    //用户退出登录
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出登录成功");
    }
}
